package com.je.gateway.filter;

import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.je.gateway.filter.loader.FilterParamsXmlLoader;
import com.je.gateway.xml.ConfigResourceLoader;
import io.vertx.core.json.JsonObject;
import org.apache.servicecomb.common.rest.filter.HttpServerFilter;
import org.apache.servicecomb.core.Invocation;
import org.apache.servicecomb.foundation.vertx.http.HttpServletRequestEx;
import org.apache.servicecomb.foundation.vertx.http.VertxServerRequestToHttpServletRequest;
import org.apache.servicecomb.swagger.invocation.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @program: jecloud-gateway
 * @author: LIULJ
 * @create: 2021/7/8
 * @description:
 */
public class GateWayParamsServerWrapperFilter implements HttpServerFilter {

    private static final Logger logger = LoggerFactory.getLogger(GateWayParamsServerWrapperFilter.class);

    private ConfigResourceLoader<Map<String, Object>> loader = new FilterParamsXmlLoader();

    public static Map<String, Object> params;

    public GateWayParamsServerWrapperFilter() {
        params = loader.load();
    }

    @Override
    public int getOrder() {
        return 3;
    }

    @Override
    public Response afterReceiveRequest(Invocation invocation, HttpServletRequestEx requestEx) {
        String keyStr = invocation.getContext().get(GatewayFilterConstants.CONTEXT_JE_PARAMS_KEY);
        List<String> noConversionList = params.get(FilterParamsXmlLoader.NO_CONVERTION_KEY) == null ? null : (List<String>) params.get(FilterParamsXmlLoader.NO_CONVERTION_KEY);
        List<String> allKeyList = new ArrayList<>();
        if (!Strings.isNullOrEmpty(keyStr)) {
            List<String> splitedKeys = Splitter.on(",").splitToList(keyStr);
            allKeyList.addAll(splitedKeys);
        }

        try {
            JsonObject jsonObject = ((VertxServerRequestToHttpServletRequest) requestEx).getContext().getBodyAsJson();
            if (jsonObject != null) {
                JSONObject jsonObject1 = JSONObject.parseObject(jsonObject.toString());
                if (jsonObject1 != null && !jsonObject1.isEmpty()) {
                    for (String key : jsonObject1.keySet()) {
                        allKeyList.add(key);
                        Object value = jsonObject.getValue(key);
                        invocation.getContext().put(key, URLEncoder.encode(Objects.toString(value)));
                    }
                }
            }
        } catch (Exception e) {

        }
        Map<String, String[]> params = requestEx.getParameterMap();
        for (Map.Entry<String, String[]> eachEntry : params.entrySet()) {
            if (!noConversionList.contains(eachEntry.getKey())) {
                invocation.getContext().put(eachEntry.getKey(), eachEntry.getValue() == null ? null : URLEncoder.encode(eachEntry.getValue()[0]));
                allKeyList.add(eachEntry.getKey());
                if (logger.isDebugEnabled()) {
                    logger.debug("conversion param {} value to context {}", eachEntry.getKey(), eachEntry.getValue()[0]);
                }
                continue;
            }
            logger.info("No conversion param {} value {}", eachEntry.getKey(), eachEntry.getValue()[0]);
        }
        keyStr = Joiner.on(",").join(allKeyList);
        invocation.getContext().put(GatewayFilterConstants.CONTEXT_JE_PARAMS_KEY, keyStr);
        return null;
    }


}
